<template>
  <el-upload
  style="display: none"                               
  class="avatar-uploader"                     
  action="http://localhost:9090/updown/updateImgFile"  
  name="img"  
  :show-file-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload"  
>
</el-upload>
<quill-editor v-model="docContent"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="handleEditorBlur($event)"
          @focus="handleEditorFocus($event)"
          @change="handleEditorChange($event)">
    </quill-editor>

</template>

<script>
import { QuillEditor } from "@vueup/vue-quill";
import  {uploadImage}  from "../../api/file/img";
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
export default {
  
  name: "App",
  components: {
    QuillEditor,
  },
  data() {
    let self = this
    return {
      fileUpload:{   //附件上传
        file:null
      },
serverUrl: 'http://localhost:9090/updown/updateImgFile',//上传图片的地址
     // 富文本编辑器配置
     editorOption: {
      placeholder:'',
      theme:'snow',
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
              ["blockquote", "code-block"], //引用，代码块
              [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
              [{ list: "ordered" }, { list: "bullet" }], //列表
              [{ script: "sub" }, { script: "super" }], // 上下标
              [{ indent: "-1" }, { indent: "+1" }], // 缩进
              [{ direction: "rtl" }], // 文本方向
              [{ size: ["small", false, "large", "huge"] }], // 字体大小
              [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
              [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
              [{ font: [] }], //字体
              [{ align: [] }], //对齐方式
              ["clean"], //清除字体样式
              ["image"], //上传图片、上传视频 ['image', 'video']
            ],
            handlers: {
              image: function (value) {    //替换原图片上传功能
                if (value) {
                  console.log(`value`, value);
                  document.querySelector('.avatar-uploader input').click() //核心
                } else {
                  this.quill.format("image", false);
                }

                  },
                  addBtn: () => {
    this.$refs.edit.quill.insertEmbed(0, 'video', 'https://xxx.mp4')
  },
             }
          },
      
        },
        
        placeholder: "请输入内容...",
 },
      msg: "",
      gridData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
      ],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formOne: {
        title: "",
        message: "",
        day: "",
        userId: "",
        type:""
      },
      formLabelWidth: "120px",
      fileList: [
      this.formLabelWidth
      
      ],
      textarea: "",
      
    };
  },

  methods: {
    handleClick(data) {
      this.dialogFormVisible = true;
      this.formOne.day = data.day;
    },
    uploadError() {
        // loading动画消失
        this.quillUpdateImg = false
        this.$message.error('图片插入失败')
    },
    beforeUpload(file) {
      this.fileUpload.file=file;
        // 显示loading动画
        this.quillUpdateImg = true
    },
    handleEditorBlur () {},
    handleEditorFocus () {},
    //这个是当初做的个文字限制后来没用就注释了
    handleEditorChange (e) {
      /*this.textLen = e.text.length - 1;
      this.beyond = this.textLen - 350;
      if (this.textLen > 350) {
        this.info.evId = '';
      } else {
        this.info.evId = this.evList[0].evId;
      }*/
    },

    show(file){
     // 添加匹粘贴板事件禁止图片粘贴
     //var uploadFile = new FormData(file);
   
//注意files是对应后台的参数名哦   
       //console.log(param);                                 // 添加form表单中其他数据
       
      console.log(`file[0]`, file[0]);
    
        let param = new FormData(); //创建form对象
        param.append("file", file); //通过append向form对象添加数据
       
     updateImg(file).then(item=>{
      console.log(`item`, item);
     }).catch(item=>{
      console.log(`item2`, item);
     })
    },
   
    // 失去焦点事件
    onEditorBlur(quill) {
      console.log("editor blur!", quill,this.message);
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      console.log("editor focus!", quill,this.message);
    },
    // 准备富文本编辑器
    onEditorReady(quill) {},
    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      
      this.content = html;
    },
    
   //上传图片之前校验
bfUpload(file) {
   
    if ("image/png" == file.type || "image/jpeg" == file.type) {
    } else {
        this.$message.error('图片插入失败,请检查文件格式');
        return;
    }
},
//正文插入图片上传成功调用
uploadSuccess(res, file){
      // 首先获取富文本编辑器的实例
      let quill = this.$refs.myQuillEditor.quill
      // 上传成功所执行
      if (res.code == 200 && res.data !== null) {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入图片res为服务器返回的数据
          quill.insertEmbed(length, 'image', res.data)
          // 光标移动至文本末端
          quill.setSelection(length + 1)
      } else {
          this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },




// 调用


  },
};
</script>
  

  <style>
.is-selected {
  color: #1989fa;
}
  .main {
    margin: 50px 300px;
  }
  .upload-demo {
    margin-top: 30px;
  }
  .ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options {
  border-color: #ccc;
  height: 125px;
  overflow: auto;
}
</style>